<template>
  <div class="flex justify-center items-center bottom-0 z-25 left-0 right-0 p-3"
       :class="{'fixed': isFixed, 'sticky': !isFixed} ">
    <div class="stats stats-vertical lg:stats-horizontal shadow bg-opacity-70 backdrop-filter m-auto">
      <div class="stat">
        <div class="stat-figure">
          <Icon :name="socialInfo.isLiked ? 'twemoji:beating-heart' : 'ph:heart-light'"
                size="36"
                class="cursor-pointer mr-1"
                @click="handleLikeTopic(socialInfo)"/>
        </div>
        <div class="stat-title">Total Likes</div>
        <div class="stat-value">{{ socialInfo.likedCount }}</div>
      </div>
      <div class="stat">
        <div class="stat-figure">
          <label :for="modalId">
            <Icon
                name="mdi-light:comment"
                size="36"
                class="cursor-pointer mr-1"/>
          </label>
        </div>
        <div class="stat-title">Total Comments</div>
        <div class="stat-value">{{ socialInfo.commentedCount }}</div>
      </div>
    </div>
  </div>
  <div>
    <!-- 评论输入以及列表弹窗 -->
    <AnnModal :modal-id="modalId" title="评论" custom-class="w-11/12 max-w-2xl">
      <section class="flex mb-10 justify-center items-end">
        <!-- 头像信息 -->
        <div class="avatar">
          <div class="avatar w-10 rounded-full ring-primary transform hover:rotate-3d mb-5 mr-3">
            <img
                v-if="userInfo"
                :src="userInfo.avatar"
                class="transition-transform duration-500 ease-in-out transform-gpu hover:scale-110" alt=""/>
            <img
                v-else
                src="/no-login.png"
                class="transition-transform duration-500 ease-in-out transform-gpu hover:scale-110" alt=""/>
          </div>
        </div>
        <!-- 输入框 -->
        <textarea
            class="textarea textarea-accent textarea-bordered textarea-md w-full max-w-2xl bg-opacity-30 backdrop-filter backdrop-blur-lg"
            placeholder="说点什么吧..."
            v-model="commentInfo.commentContent"/>
        <button class="btn btn-outline w-20 ml-6" @click="handleCommentClick">
          评 论
        </button>
      </section>
      <!-- 列表展示 -->
      <section>
        <AnnCommentItem
            v-for="item in socialInfo.commentList"
            :key="item.commentId"
            :comment-item="item"
            :author-id="socialInfo.authorId"
            @refresh="onRefresh"></AnnCommentItem>
      </section>
      <!-- 列表展示结束-->
    </AnnModal>
  </div>
</template>

<script setup lang="ts">
import {getUserInfoFromCookie} from "~/utils/cookie";
import {debounce} from "lodash";
import {comment, like} from "~/api/article";
import type {BlogCommentQueryWebBo, BlogCommentWebBo, BlogCommentWebVO, SocialInfo,} from "~/api/comment/types";
import {queryCommentList} from "~/api/comment";
import type {BlogUserWebVO} from "~/api/user/types";
import {inBrowser} from "~/utils/nuxt/constants";
import {showMessage} from "~/utils/toast";

let isFixed = ref<boolean>(true);

const modalId = ref<string>("articleCommentModal")

const commentInfo = reactive<BlogCommentWebBo>({
  topicId: "",
  commentContent: "",
  parentId: "",
  answerId: "",
});
// 定义 BlogCommentQueryWebBo 常量
const commentQuery = reactive<BlogCommentQueryWebBo>({
  topicId: "",
  topic: "0",
});

// 登录用户信息
const userInfo = ref<BlogUserWebVO>();
const props = defineProps({
  socialInfo: {
    type: Object as () => SocialInfo,
    required: true,
  },
});

// 获取用户信息
const getUserInfo = async () => {
  userInfo.value = await getUserInfoFromCookie();
};
getUserInfo()
// 获取评论列表的方法
const getCommentList = async () => {
  commentQuery.topicId = props.socialInfo.topicId as string;
  const {data: res} = await useAsyncData("commentList", () =>
      queryCommentList(commentQuery)
  );
  if (res.value?.code == 200) {
    props.socialInfo.commentList = res.value.data as BlogCommentWebVO[];
    const commentList = props.socialInfo.commentList;
    //在前端计算下评论条数
    const totalChildrenLength = commentList.reduce((total, comment) => {
      return total + comment.children.length;
    }, 0);
    props.socialInfo.commentedCount = totalChildrenLength + commentList.length;
  }
};

// 点击评论
const handleCommentClick = async () => {
  // 发表评论
  commentInfo.topicId = props.socialInfo.topicId;
  const {data: data} = await useAsyncData("articleDetailComment", () =>
      comment(commentInfo)
  );
  if (data.value?.code == 200) {
    // 获取评论列表
    await getCommentList();
    commentInfo.commentContent = "";
    showMessage("评论成功");
  }
};

// 子组件的回复监听
const onRefresh = async () => {
  // 获取评论列表
  await getCommentList();
};

// 点赞
const handleLikeTopic = async (socialInfo: SocialInfo) => {
  const {data} = await useAsyncData("articleDetailLike", () =>
      like(socialInfo.topicId)
  );
  if (data.value?.code == 200) {
    socialInfo.isLiked = !socialInfo.isLiked;
    socialInfo.likedCount += socialInfo.isLiked ? 1 : -1;
  }
};

if (inBrowser) {
  const handleScroll = debounce(() => {
    const scrollTop =
        window.scrollY ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
    const windowHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
    const documentHeight = Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight
    );
    isFixed.value = scrollTop + windowHeight + 300 <= documentHeight;
  }, 30); // 调整延迟时间(单位：毫秒)
  onMounted(() => {
    window.addEventListener("scroll", handleScroll);
  });
  onUnmounted(() => {
    window.removeEventListener("scroll", handleScroll);
  });
}

</script>
